package com.lys.book.utils;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class ConnDB {
	public static Connection getConnection() {
		Connection conn = null;
		try {

			Class.forName("com.mysql.cj.jdbc.Driver");
			String url ="jdbc:mysql://localhost:3306/hw_book_sys?useSSL=false&serverTimezone=Asia/Shanghai";
			String user = "root";
			String password = "root";
			conn = DriverManager.getConnection(url,user,password);
		} catch (ClassNotFoundException  e) {
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return conn;
	}
	public  static void closeDB(ResultSet rs,Statement pst,Connection conn) {
		try {
			if(rs!=null) {
				rs.close();
			}
			if(pst!=null) {
				pst.close();
			}
			if(conn!=null) {
				conn.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static Object[][] convertResultSetToObjectArray(ResultSet resultSet) throws SQLException {
		ResultSetMetaData metaData = resultSet.getMetaData();
		int columnCount = metaData.getColumnCount();

		List<Object[]> rows = new ArrayList<>();
		while (resultSet.next()) {
			Object[] rowData = new Object[columnCount];
			for (int i = 0; i < columnCount; i++) {
				rowData[i] = resultSet.getObject(i + 1);
			}
			rows.add(rowData);
		}

		return rows.toArray(new Object[0][]);
	}

	public static ResultSet query(String sql, Object[] objects) throws SQLException {
		Connection conn = ConnDB.getConnection();
		PreparedStatement pst = conn.prepareStatement(sql,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
		ResultSet resultSet=null;
//        判断Object是否为空，为空直接执行sql语句
		if (objects == null) {
			resultSet = pst.executeQuery();
		} else {
			for (int i = 0; i < objects.length; i++) {
				pst.setObject(i+1,objects[i]);
			}
			resultSet = pst.executeQuery();
		}
		return resultSet;
	}


	public static void main(String[] args) {
		System.out.println(ConnDB.getConnection());
	}
}
